// store/modules/auth.js
import request from '../utils/request'
import { ElNotification } from 'element-plus'
// store/modules/auth.js
const state = () => ({
  user: null,
  opid: null,
  token: localStorage.getItem('token') || null
})

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER(state, user) {
    state.user = user.username
    state.opid = user.opid
  },
  CLEAR_AUTH(state) {
    state.user = null
    state.token = null
    localStorage.removeItem('token')
  }
}

const actions = {
  async login({ commit }, credentials) {

      const response = await request.post('/login/login', credentials)
      console.log('response',response)
      if (response.code == 200) {
        commit('SET_TOKEN', response.data.token)
        return true
      }
      ElNotification.error({title: '登录失败',message: response.message})
  },
  async fetchUser({ commit, state }) {
    if (state.token) {
      const response = await request.get('/setting/user/queryUserInfo')
      commit('SET_USER', response.data)
    }
  },
  logout({ commit }) {
    commit('CLEAR_AUTH')
    router.push('/login')
  }
}

const getters = {
  currentUser: state => state.user,
  isAuthenticated: state => !!state.token
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
